﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OT.Data;
using OT.Areas.Admin.Models;
using OT.Areas.Student.Models;
using PagedList;
using System.Data.SqlClient;
namespace OT.Areas.Student.Controllers
{
    #region class_Available
    public class AvailableController : Controller
    {
        #region Declaration
        OTEntitiesme OTDb = new OTEntitiesme();
        int LanguageID = Utilities.GetLanguageID();
        double TotalMarks = 0;
        int qid = 0;
        public static List<sp_GetInitialData_Result> allData = null;
        #endregion

        #region Index
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(int pageNumber, int pageSize, string searchString, int pgindex, string columnFilter)
        {
            var Test = (List<Tests>)null;
            int recount = 0;
            try
            {
                int UserID = 0;
                if (Request.Cookies["LoginSesID"] != null)
                {
                    UserID = Convert.ToInt16(Request.Cookies["LoginSesID"].Value);
                    //Cookie
                    HttpCookie myCookie = new HttpCookie("LoginSesID");
                    myCookie.Value = UserID.ToString();
                    myCookie.Expires = DateTime.Now.AddDays(1d); 
                    Response.Cookies.Add(myCookie);
                }
                else
                {
                    TempData["notice"] = "Time Out ,Please Login";
                    Response.Redirect("~/Home");
                }
                Test = (from c in OTDb.TestUsers
                        where c.UserID.Value.Equals(UserID) && c.Test.LanguageID.Value.Equals(LanguageID)
                        select new Tests
                        {
                            TestID = c.TestID.Value,
                            TestName = c.Test.TestName,
                            Description = c.Test.Description,
                            Status = c.Test.Status.Value,
                            TestType1 = c.Test.TestType.TestType1
                        }).ToList();
                if (!String.IsNullOrEmpty(searchString))
                    Test = Test.Where(r => r.TestName.Contains(searchString)).ToList();
                recount = Test.Count;
                Test = Test.Skip<Tests>(pgindex * (pageNumber - 1))
                    .Take<Tests>(pgindex).ToList<Tests>();
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return Json(new
            {
                PageNumber = pageNumber,
                PageSize = pageSize,
                PgIndex = pgindex,
                Data = Test,
                RecordCount = recount
            });
        }

        #endregion
        
        #region Continue
        public ActionResult ContinueTest(int TestID)
        {
            ViewBag.TestID = TestID;
            int totque = 0;
            int mark = 0;
            try
            {
                var infoData = (from c in OTDb.Tests
                                join ttyp in OTDb.Tests
                                on c.TestID equals TestID into output
                                join sub in OTDb.Subjects
                                on c.SubjectID equals sub.SubjectID
                                join top in OTDb.Topics
                                on c.TopicID equals top.TopicID
                                from j in output.DefaultIfEmpty()
                                where c.TestID == TestID
                                select new
                                {
                                    SubjectName = sub.SubjectName,
                                    TopicName = top.TopicName,
                                    TestName = c.TestName,
                                    TotalQ = c.TotalQuestion,
                                    Duration = c.Duration.Value,
                                    Positive = c.PositiveMark.Value,
                                    Nagetive = c.NegativeMark.Value,
                                    passScore = c.PassingScore.Value,
                                    Dis = c.Description,
                                    testID = c.TestID
                                }
                        ).ToList();
                var Infodata1 = infoData.Where(r => r.testID == TestID).FirstOrDefault();
                if (infoData != null)
                {
                    totque = (from t in OTDb.TestQuestions
                              where t.TestID.Value.Equals(TestID)
                              select t).Count<TestQuestion>();
                    mark = (from t in OTDb.Tests
                            where t.TestID.Equals(TestID)
                            select t.PositiveMark).FirstOrDefault().Value;
                    ViewBag.SubjectName = Infodata1.SubjectName;
                    ViewBag.TopicName = Infodata1.TopicName;
                    ViewBag.TestName = Infodata1.TestName;
                    ViewBag.TotalQ = totque;
                    ViewBag.Duration = Infodata1.Duration;
                    ViewBag.passScore = Infodata1.passScore;
                    ViewBag.Positive = Infodata1.Positive;
                    ViewBag.Nagetive = Infodata1.Nagetive;
                    ViewBag.Dis = Infodata1.Dis;
                    ViewBag.outoff = totque * mark;
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return View();
        }
        public ActionResult StartTest(int TestID = 0, string value = "", int TestQuestionID = 0, string QuestionName = "")
        {
            try
            {
                int atmtid = int.Parse(OTDb.AttemptMsts
                               .OrderByDescending(p => p.AttemptID)
                               .Select(r => r.AttemptID)
                               .First().ToString());
                HttpCookie myCookie = new HttpCookie("AttemptID");
                // Set the cookie value.
                atmtid = atmtid + 1;
                myCookie.Value = atmtid.ToString();
                // Set the cookie expiration date.
                myCookie.Expires = DateTime.Now.AddDays(1d);
                // Add the cookie.
                Response.Cookies.Add(myCookie);
            }
            catch (Exception e)
            {
                Utilities.InsertErrorLog(e);
            }
           return PartialView();
        }

        public int getTestTime(int TestID)
        {
            int time = (from t in OTDb.Tests
                        where t.TestID.Equals(TestID)
                        select t.Duration.Value).FirstOrDefault();
            return time * 60;
        }
        #endregion

        #region GETQUE&Ans
        public JsonResult GetQuestionAndAnswer(int TestID, int UserID)
        {
            try
            {
                allData = OTDb.sp_GetInitialData(TestID, UserID).ToList<sp_GetInitialData_Result>();
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return Json(new{
                allData,
                  quedata = allData.Select(x => x.QuestionID).ToList()
            }, JsonRequestBehavior.AllowGet);
        }
       
        public JsonResult GetQuestionAndAnswer1(int AttemptID,int QuestionID,int TestID,string ButtonType,int ChoosenAns,int Position)
        {
            List<sp_ManageAllQuestion_Result> data1 = new List<sp_ManageAllQuestion_Result>() ;

            int questionForAdd = 0;
            if (ButtonType == "skip" && Position == 0)
            {
                questionForAdd = (int)allData[0].QuestionID;
            }
            else if (ButtonType == "End")
            {
                questionForAdd = (int)allData[0].QuestionID;
            }
            else if (ButtonType == "Prev")
            {
                int pos = Position - 2;
                questionForAdd = (int)allData[pos].QuestionID;
            }
            else
            {
                questionForAdd = (int)allData[Position].QuestionID;
            }
            try
            {
                data1 = OTDb.sp_ManageAllQuestion(AttemptID, QuestionID, TestID, ButtonType, ChoosenAns, questionForAdd).ToList<sp_ManageAllQuestion_Result>();
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            if (ButtonType == "QueNumber")
            {
                var datatest = allData[Position];
                return Json(new { data1, datatest }, JsonRequestBehavior.AllowGet);
            }
            else if (ButtonType == "End")
            {
                var datatest = allData[0];
                return Json(new { data1, datatest }, JsonRequestBehavior.AllowGet);
            }
            else if (ButtonType == "Prev")
            {
                var datatest = allData[Position-2];
                return Json(new { data1, datatest }, JsonRequestBehavior.AllowGet);
            }
            else if (ButtonType == "skip")
            {
                var datatest = allData[Position];
                return Json(new { data1, datatest }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                var datatest = allData[Position];
                return Json(new { data1, datatest }, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region EndTest
        public ActionResult EndTest(int AttemptID)
        {
            var data = OTDb.sp_EndTest(AttemptID).ToList<sp_EndTest_Result>();
            double TotalScore=(int)data[0].TotalScore;
            double TotalMarks=(int)data[0].TotalMarks;
            double Percantage = Convert.ToDouble((Math.Round((TotalScore / TotalMarks) * 100, 2)));
            var Result = (Percantage >= data[0].PassingScore) ? "Passed" : "Failed";
            ViewBag.PassingScore = data[0].PassingScore;
            ViewBag.TotalQuestion = data[0].TotalQuestion;
            ViewBag.TotalMarks = data[0].TotalMarks;
            ViewBag.AttemptedQuestions = data[0].AttemptedQuestions;
            ViewBag.UnAttemptedQuestions = data[0].UnAttemptedQuestions;
            ViewBag.CorrectAnswers = data[0].CorrectAnswers;
            ViewBag.WrongAnswers = data[0].WrongAnswers;
            ViewBag.totalPositiveMarks = data[0].totalPositiveMarks;
            ViewBag.totalNegativeMarks = data[0].totalNegativeMarks;
            ViewBag.TotalScore = data[0].TotalScore;
            if (Percantage > 0)
            {
                ViewBag.Percantage = Math.Round(Percantage, 2);
            }
            else
            {
                ViewBag.Percantage = "";
            }
            ViewBag.Result =Result;
            return View();
        }

        public ActionResult EndTestModel()
        {
            return PartialView();
        }
        #endregion
    }
    #endregion
}
